import { getData, mock } from '../data/index';
import md5 from '../utils/md5';
import fail from './fail';
import success from './success';

export const request = (params = {}) => {

  return new Promise((resolve, reject) => {
    const app = getApp();
    const data = params.data || {};
    const paths = params.api.split('/');
    data.token = md5(paths[paths.length - 1] + "#ad2*4aroyalpey(^@").toLowerCase();

    const opts = {
      url: params.root || app.root + '/' + params.api,
      data,
      method: params.method ? params.method.toUpperCase() : 'POST',
      success: (res) => {
        wx.hideLoading();
        const { data } = res;

        if (data.error) {
          fail(data, reject, params, get, post);
        } else {
          success(data, resolve, params);
        }
      },
      fail: (error) => {
        fail({ error }, reject, params, get, post);
      },
      complete: () => {
        // wx.hideLoading();
      }
    };

    if (!params.quietly){
      wx.showLoading({
        title: '请稍后……',
        mask: true
      })
    }
    wx.request(opts);
  });
};

export const get = (config) => {
  if (mock || config.useMockData) {
    return getData(config.api, config.data);
  }

  config.method = 'GET';
  return request(config);
};

export const post = (config) => {
  if (mock || config.useMockData) {
    return getData(config.api, config.data);
  }

  config.method = 'POST';
  return request(config);
};